跳到主要内容

工作流自定义代码书写规范

背景:出于安全考虑,【python 自定义技能代码】&&【高级编排-代码节点】,对代码编写进行规范说明

支持的 Python Package

1. 内置函数与类型

  • dict
  • sorted
  • filter
  • map
  • enumerate

2. 标准库模块

数据处理

  • json
  • decimal
  • uuid
  • base64
  • hashlib

字符串处理

  • re (正则表达式)
  • string
  • textwrap
  • difflib (差异比较)

数据结构与算法

  • copy
  • bisect (二分查找)
  • heapq (堆队列)
  • statistics (统计计算)

数学计算

  • math
  • operator (运算符函数)

日期与时间

  • datetime
  • time
  • calendar

其他工具

  • random (随机数生成)
  • requests (HTTP 请求)

3. 类型注解 (typing 模块)

  • typing (模块本身)
  • Any
  • Union
  • Optional
  • Literal
  • Final
  • ClassVar
  • TypeVar
  • Generic
  • Protocol
  • runtime_checkable
  • overload
  • cast
  • TYPE_CHECKING
  • NoReturn
  • List
  • Dict
  • Set
  • Tuple
  • FrozenSet
  • Deque
  • Counter
  • ChainMap
  • OrderedDict
  • DefaultDict
  • MutableMapping
  • MutableSequence
  • MutableSet
  • Mapping
  • Sequence
  • AbstractSet
  • Collection
  • Container
  • Iterable
  • Iterator
  • Reversible
  • Sized
  • Hashable
  • Callable
  • Awaitable
  • Coroutine
  • AsyncIterable
  • AsyncIterator
  • AsyncGenerator
  • Generator
  • ContextManager
  • AsyncContextManager

语法规范

由于使用了安全的环境隔离等限制,需要编写者遵循相关规范进行代码编写。前提:仅支持内置语法和内置库,以及有限的标准库。

  1. 使用 math 模块
import math

def calculate(a, b):
result = math.fsum([a, b])
return result

错误的写法:

from math import fsum

def calculate(a, b):
result = fsum([a, b])
return result

解释:当前代码块的导入限制,在 import 包的时候,仅导入了父级包的导入,不支持 from a import b 的语法。

  1. 使用 datetime

正确的写法:

import typing
from datetime import datetime


def get_weather(location: str, date: typing.Optional[str] = None) -> dict:
# 处理默认日期
if date is None:
formatted_date = datetime.datetime.now().strftime("%Y-%m-%d")
else:
try:
# 尝试解析常见日期格式
if len(date) == 8 and date.isdigit():
# 处理 YYYYMMDD 格式
date_obj = datetime.datetime.strptime(date, "%Y%m%d")
else:
# 尝试标准格式 YYYY-MM-DD
date_obj = datetime.datetime.strptime(date, "%Y-%m-%d")
formatted_date = date_obj.strftime("%Y-%m-%d")
except ValueError:
# 如果格式不匹配,使用原始输入(可能导致API调用失败)
formatted_date = date

# 这里是模拟数据,实际应用中可能会调用天气API
weather_data = {
"location": location,
"date": formatted_date,
"forecast": "sunny",
"temperature": "25°C",
"wind": "light breeze"
}
return weather_data

错误的写法:

from typing import Optional, List, Dict, Any, Union, Callable
from datetime import datetime
...省略...